package com.zzm.shortlink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzm.shortlink.admin.common.biz.user.UserContext;
import com.zzm.shortlink.admin.common.convention.exception.ClientException;
import com.zzm.shortlink.admin.common.convention.result.Result;
import com.zzm.shortlink.admin.dao.entity.GroupDO;
import com.zzm.shortlink.admin.dao.mapper.GroupMapper;
import com.zzm.shortlink.admin.dto.req.ShortLinkGroupRemoveReqDTO;
import com.zzm.shortlink.admin.dto.req.ShortLinkGroupSortReqDTO;
import com.zzm.shortlink.admin.dto.req.ShortLinkGroupUpdateReqDTO;
import com.zzm.shortlink.admin.dto.resp.ShortLinkGroupRespDTO;
import com.zzm.shortlink.admin.remote.dto.ShortLinkActualRemoteService;
import com.zzm.shortlink.admin.remote.dto.ShortLinkRemoteService;
import com.zzm.shortlink.admin.remote.dto.resp.ShortLinkGroupCountQueryRespDTO;
import com.zzm.shortlink.admin.service.GroupService;
import com.zzm.shortlink.admin.toolkit.RandomGenerator;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Value;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

import static com.zzm.shortlink.admin.common.constant.RedisCacheConstant.LOCK_GROUP_CREATE_KEY;
/**
 * 短链接分组接口实现层
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class GroupServiceImpl extends ServiceImpl<GroupMapper, GroupDO> implements GroupService {

    private final RedissonClient redissonClient;

    @Value("${short-link.group.max-num}")
    private Integer groupMaxNum;


    private final ShortLinkActualRemoteService shortLinkActualRemoteService;


    /**
     *添加分组
     * @param groupName 分组名称
     */
    @Override
    public void saveGroup(String groupName,String username) {
        RLock lock = redissonClient.getLock(String.format(LOCK_GROUP_CREATE_KEY, username));
        lock.lock();
        try{
            LambdaQueryWrapper<GroupDO> queryWrapper = Wrappers.lambdaQuery(GroupDO.class)
                    .eq(GroupDO::getUsername, username)
                    .eq(GroupDO::getDelFlag, 0);
            List<GroupDO> groupDOList = baseMapper.selectList(queryWrapper);
            if(CollUtil.isNotEmpty(groupDOList) && groupDOList.size() >= groupMaxNum){
                throw new ClientException(String.format("已超出最大分组数：%d", groupMaxNum));
            }
            String gid;
//        生成一个数据库中不存在的gid
            do {
                gid = RandomGenerator.generateRandom();
            } while (hasGid(gid,username));
            //如果没有传 那就从上下文中获取
            if(username.isEmpty()) {
                username = UserContext.getUsername();
            }
            //链式添加属性 与GroupDO中的三个注解有关
            GroupDO groupDO = GroupDO.builder()
                    .gid(gid)
                    .name(groupName)
                    .username(username)
                    .sortOrder(0)
                    .build();
            baseMapper.insert(groupDO);
        }finally {
            lock.unlock();
        }

    }


    @Override
    public List<ShortLinkGroupRespDTO> listGroup() {
        Wrapper<GroupDO> wrapper = Wrappers.lambdaQuery(GroupDO.class)
                // TODO 从当前上下文获取用户名
                .eq(GroupDO::getUsername,UserContext.getUsername())
                .eq(GroupDO::getDelFlag,0)
                .orderByAsc(GroupDO::getUpdateTime)
                .orderByDesc(GroupDO::getSortOrder);

        List<GroupDO> groupDOList = baseMapper.selectList(wrapper);
        Result<List<ShortLinkGroupCountQueryRespDTO>> listResult = shortLinkActualRemoteService
                .listGroupShortLinkCount(groupDOList.stream().map(GroupDO::getGid).toList());
        List<ShortLinkGroupRespDTO> shortLinkGroupRespDTOList = BeanUtil.copyToList(groupDOList, ShortLinkGroupRespDTO.class);
        shortLinkGroupRespDTOList.forEach(each -> {
            Optional<ShortLinkGroupCountQueryRespDTO> first = listResult.getData().stream()
                    .filter(item -> Objects.equals(item.getGid(), each.getGid()))
                    .findFirst();
            first.ifPresent(item -> each.setShortLinkCount(first.get().getShortLinkCount()));
        });
        return shortLinkGroupRespDTOList;
    }

   /*
     * 修改分组名称
     * @param requestParam 请求参数
     */
    @Override
    public void updateGroup(ShortLinkGroupUpdateReqDTO requestParam) {
        Wrapper<GroupDO> wrapper = Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .eq(GroupDO::getDelFlag,0)
                .eq(GroupDO::getGid,requestParam.getGid());
        GroupDO groupDO = new GroupDO();
        groupDO.setName(requestParam.getName());
        baseMapper.update(groupDO, wrapper);
    }
    /*
     * 删除分组
     * @param requestParam 请求参数
     * 这里的删除实际上是将getDelFlag设置为1 不是真的删除
     */
    @Override
    public void removeGroup(String gid) {
        LambdaUpdateWrapper<GroupDO> updateWrapper = Wrappers.lambdaUpdate(GroupDO.class)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .eq(GroupDO::getGid, gid)
                .eq(GroupDO::getDelFlag, 0);
        GroupDO groupDO = new GroupDO();
        groupDO.setDelFlag(1);
        baseMapper.update(groupDO, updateWrapper);
    }


    /**
     *
     * @param gid 分组标识
     * @return 如果数据库中存在改gid 那么返回true 否则返回false
     */
    private boolean hasGid (String gid,String username) {
        LambdaQueryWrapper<GroupDO> queryWrapper = Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getGid, gid)
                // TODO 设置用户名
                .eq(GroupDO::getUsername, Optional.ofNullable(username).orElse(UserContext.getUsername()));
        GroupDO hasGroupFlag = baseMapper.selectOne(queryWrapper);
        return hasGroupFlag != null;
    }

    /**
     * 用户链接分组排序 0
     * @param requestParam 短链接分组排序参数
     */
    @Override
    public void sortGroup(List<ShortLinkGroupSortReqDTO> requestParam) {
        requestParam.forEach(each -> {
            GroupDO groupDO = GroupDO.builder()
                    .sortOrder(each.getSortOrder())
                    .build();
            LambdaUpdateWrapper<GroupDO> updateWrapper = Wrappers.lambdaUpdate(GroupDO.class)
                    .eq(GroupDO::getUsername, UserContext.getUsername())
                    .eq(GroupDO::getGid, each.getGid())
                    .eq(GroupDO::getDelFlag, 0);
            baseMapper.update(groupDO, updateWrapper);
        });
    }

}
